package com.financing.wap.web.controller.api;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import com.financing.wap.common.ResultMap;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.util.Constants;
import com.financing.wap.util.VerifyCodeUtils;

/**
 * 校验码请求
 * @author Mars
 * @createDate 2014年10月8日
 */
@Controller("apiVerifyCodeController")
@RequestMapping("/api/verifyCode")
public class VerifyCodeController extends HttpServlet{
	private static final long serialVersionUID = -4314674213607819634L;
	
	Logger logger = Logger.getLogger(getClass());

	@RequestMapping("service")
	public void view(HttpServletRequest request, HttpServletResponse response){

		Session session = SessionUtil.getSession();
		ResultMap result = new ResultMap();
		OutputStream os = null;
		try {
			logger.info("==>start mode versifyCode<==");
			response.setHeader("Pragma", "No-cache");  
			response.setHeader("Cache-Control", "no-cache");  
			response.setDateHeader("Expires", 0);  
			response.setContentType("image/jpeg");  

			//生成随机字串  
			String verifyCode = VerifyCodeUtils.generateVerifyCode(4);  
			logger.info("==> mode versifyCode<=="+verifyCode);
			//存入会话session  
			session.setAttribute(Constants.SESSION_KEY_VERIFYCODE, verifyCode.toLowerCase());  
			//生成图片  (图片默认长、宽)
			int w = 80, h = 34;
			String wStr = request.getParameter("w");
			String hStr = request.getParameter("h");
			if(StringUtils.isNotBlank(wStr)&&StringUtils.isNotBlank(hStr)){
				w=Integer.parseInt(wStr);
				h=Integer.parseInt(hStr);
			}
			os = response.getOutputStream();
			VerifyCodeUtils.outputImage(w, h, os, verifyCode);  
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.error("==>error messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}finally{
			if(os!=null){
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					logger.warn("IO CLOSE ERROR:"+e.getLocalizedMessage());
					
				}
			}
			
		}
		return ;
	} 


}
